"""
对dcm图片数据进行处理和初始化
"""


import cv2
from dcm_utils import dicom2array, dicom_metainfo
import json
import configparser
from datasets import get_info
import numpy as np
import glob
import os


conf = configparser.ConfigParser()
conf.read('../config.text')


def test_json():
    """测试json的用法"""
    d = {}
    for i in range(1000):
        text = 'hello' + str(i)
        lbl = {str(i): text}
        d = dict(list(d.items()) + list(lbl.items()))
    json.dump(d, open('./test.json', 'w'), sort_keys=True, indent=4)

def get_jpg_and_json(result):
    """
    返回图片以及坐标点组成的列表
    :return:
    """

    img_dir = result.index[0]  # 获取图片的地址
    print(img_dir)
    img_arr = dicom2array(img_dir)  # 获取具体的图片数据，二维数据
    tags = result[0][0]['data']['point']  # 获取图片的标签
    print("len of result: ", len(result))
    print("len of img_drr", len(img_dir))

    fj = open('./test.json', 'w')

    # 添加到列表
    annos, anno, temp = [], [], []  # annos存放坐标列表
    d = {}
    for i in range(len(result)):
        tags = result[i][0]['data']['point']
        index = result.index[i]
        anno = []
        img = dicom2array(index)
        x, y = img.shape
        img = cv2.resize(img, (368, 368))
        for tag in tags:
            temp = []
            coords = tag['coord']
            print(x, y)
            print(coords)
            coords[0] = coords[0] * 368 // y
            coords[1] = coords[1] * 368 // x
            print("after change: ", coords)
            for coord in coords:
                # print(coord)
                temp.append(coord)
            anno.append(temp)

        # 数字格式化
        i = '{:0>4d}'.format(i)
        key = 'L' + str(i)

        # 保存训练图片
        file_name = './image/' + key + '.jpg'
        cv2.imwrite(file_name, img)

        # 生成label.json
        lbl = {i: anno}
        d = dict(list(d.items()) + list(lbl.items()))

        json.dump(d, fj, sort_keys=True, indent=4)

        print(anno)
        annos.append(anno)

    fj.close()

    return annos

def get_jpg_and_json_2(result):
    """
    返回坐标点组成的列表
    :return:
    """

    img_dir = result.index[0]  # 获取图片的地址
    print(img_dir)
    img_arr = dicom2array(img_dir)  # 获取具体的图片数据，二维数据
    tags = result[0][0]['data']['point']  # 获取图片的标签
    print("len of result: ", len(result))
    print("len of img_drr", len(img_dir))

    # 添加到列表
    annos, anno, temp = [], [], []  # annos存放坐标列表
    d = {}
    for i in range(len(result)):
        tags = result[i][0]['data']['point']
        index = result.index[i]
        anno = []
        img = dicom2array(index)

        # 数字格式化
        i = '{:0>4d}'.format(i)
        key = 'L' + str(i)

        # 保存训练图片
        file_name = './image_test_recovery/' + key + '.jpg'
        cv2.imwrite(file_name, img)

        # # 生成label.json
        # lbl = {i: anno}
        # d = dict(list(d.items()) + list(lbl.items()))
        # json.dump(d, open('./test.json', 'w'), sort_keys=True, indent=4)

        # 生成map.json
        lbl = {key: index}
        d = dict(list(d.items()) + list(lbl.items()))
        json.dump(d, open('./map_recovery.json', 'w'), sort_keys=True, indent=4)


        print(anno)
        annos.append(anno)

    return annos

def get_jpg(trainPath):
    dcm_paths = glob.glob(os.path.join(trainPath, "**", "**.dcm"))
    d = {}
    count = 1
    for p in dcm_paths:
        i = count
        # 数字格式化
        img = dicom2array(p)
        i = '{:0>4d}'.format(i)
        key = 'L' + str(i)

        # 生成map.json
        lbl = {key: p}
        d = dict(list(d.items()) + list(lbl.items()))
        json.dump(d, open('./map_recovery.json', 'w'), sort_keys=True, indent=4)

        # 保存训练图片
        img = cv2.resize(img, (368, 368))
        file_name = './image_test_recovery/' + key + '.jpg'
        cv2.imwrite(file_name, img)
        count += 1


if __name__ == '__main__':

    train_path = conf.get("FL_CONFIG", "TRAIN_PATH")
    json_path = conf.get("FL_CONFIG", "JSON_PATH")
    # train_path = '../data/train_data/lumbar_train150'
    # json_path = '../data/train_data/lumbar_train51_annotation.json'

    # test_metainfo()
    # print_tag()
    # pass
    result = get_info(train_path, json_path)
    
    get_jpg_and_json(result)